//
//  DataBaseManager.m
//  18SQL通讯录作业
//
//  Created by dllo on 16/8/9.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "DataBaseManager.h"
#import "Model.h"

@implementation DataBaseManager
+ (DataBaseManager *)shareManager
{
    static DataBaseManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[DataBaseManager alloc] init];
    });
    return manager;
}
- (BOOL)openDataBase
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *dbPath = [path stringByAppendingPathComponent:@"contact.db"];
    NSLog(@"%@",dbPath);
    int result = sqlite3_open([dbPath UTF8String], &dbPoint);
    return [self isOperationResult:result alertText:@"打开"];
    return YES;
}
- (BOOL)closeDataBase
{
    int result = sqlite3_close(dbPoint);
    return [self isOperationResult:result alertText:@"关闭"];
}
- (BOOL)createTable
{
    NSString *creatSQL = @"creat table if not existe model name text,phoneNumber text,gender text,age text";
    int result = sqlite3_exec(dbPoint, [creatSQL UTF8String], NULL, NULL, NULL);
    return [self isOperationResult:result alertText:@"创建表"];
}
- (BOOL)insertModel:(Model *)model
{
    NSString *insertSQL = [NSString stringWithFormat:@"insert into model(name,phoneNumber,gender,age) values('%@','%@','%@','%@')",model.name,model.phoneNumber,model.gender,model.age];
    int result = sqlite3_exec(dbPoint, [insertSQL UTF8String], NULL, NULL, NULL);
    return [self isOperationResult:result alertText:@"插入"];
}

- (BOOL)isOperationResult:(int)result alertText:(NSString *)text
{
    BOOL isOperation = YES;
    if (result == SQLITE_OK) {
         NSLog(@"数据库%@成功",text);
    } else {
         NSLog(@"数据库%@失败----%d",text,result);
        isOperation = NO;
    }
    return isOperation;
        
}
- (__kindof NSArray *)selectAll
{
    NSString *selectAllSQL = @"select * from model";
    sqlite3_stmt *stmt = NULL;
    int result = sqlite3_prepare(dbPoint, [selectAllSQL UTF8String], -1, &stmt, NULL);
    NSMutableArray *modelArray = [NSMutableArray array];
    if (result == SQLITE_OK) {
        while (sqlite3_step(stmt)) {
            const unsigned char *name = sqlite3_column_text(stmt, 0);
            const unsigned char *photoNumber = sqlite3_column_text(stmt, 1);
            const unsigned char *gender = sqlite3_column_text(stmt, 2);
            const unsigned char *age = sqlite3_column_text(stmt, 3);
            Model *model = [[Model alloc] initWithName:[NSString stringWithFormat:@"%s",name] gender:[NSString stringWithFormat:@"%s",gender] phoneNumber:[NSString stringWithFormat:@"%s",photoNumber] age:[NSString stringWithFormat:@"%s",age]];
            [modelArray addObject:model];
        }
    }
    sqlite3_finalize(stmt);
    return modelArray;
    
    
    
}
@end
